package servletAmministratore;

import gestioneContesto.GestoreContesto;

import java.io.IOException;
import java.util.ArrayList;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import logicaUtenteReg.GestoreProfiloRemote;

/**
 * Servlet implementation class AmiciDaProfiloAmmServlet
 */
public class AmiciDaProfiloAmmServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private RequestDispatcher dispatcher;
	private GestoreContesto contesto;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AmiciDaProfiloAmmServlet() {
        
    	super();
        contesto = new GestoreContesto();
        
    }

    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			eseguiRichiesta(request, response);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			eseguiRichiesta(request, response);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void eseguiRichiesta(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NamingException {
		
		GestoreProfiloRemote gestore = contesto.getGestore(GestoreProfiloRemote.class, "GestoreProfiloRemote");
		
		String id = request.getParameter("id");
		String utente = request.getParameter("utente");
		
		//Cerco gli amici dell'utente
		ArrayList<String> amici = gestore.listaAmici(utente);
		
		if(amici != null) {
			
			for(int i = 0; i < amici.size(); i++) {
				
				request.setAttribute("el" + i, amici.get(i));
				
			}
			
			request.setAttribute("size", amici.size());
			
		}
		else {
			
			request.setAttribute("size", 0);
			
		}
		
		request.setAttribute("id", id);
		dispatcher = request.getRequestDispatcher("AmiciDaAmm.jsp");
		dispatcher.forward(request, response);
		
	}

}
